<template>
  <div class="auth-container">
    <el-card class="auth-card">
      <template #header>
        <div class="auth-header">
          <h2>📝 注册</h2>
          <p>创建新账户</p>
        </div>
      </template>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="form.username" 
            placeholder="3-50个字符"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="form.password" 
            type="password" 
            placeholder="至少6个字符"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="form.confirmPassword" 
            type="password" 
            placeholder="再次输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="form.email" 
            type="email" 
            placeholder="your@email.com"
            clearable
          />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input 
            v-model="form.nickname" 
            placeholder="选填"
            clearable
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="form.phone" 
            placeholder="选填"
            clearable
          />
        </el-form-item>

        <el-form-item label="钱包地址" prop="walletAddress">
          <el-input 
            v-model="form.walletAddress" 
            placeholder="可稍后在个人中心绑定"
            clearable
          >
            <template #append>
              <el-button @click="getWalletAddress" :disabled="gettingWallet">
                {{ gettingWallet ? '获取中...' : '从MetaMask获取' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleRegister" 
            :loading="loading"
            style="width: 100%"
            size="large"
          >
            {{ loading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>

        <el-divider>或</el-divider>

        <el-form-item>
          <el-button 
            @click="goToLogin" 
            style="width: 100%"
            size="large"
          >
            已有账号？去登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import userStore from '../store/userStore';
import web3Service from '../services/web3Service';

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Register',
  setup() {
    const router = useRouter();
    const formRef = ref(null);
    const loading = ref(false);
    const gettingWallet = ref(false);

    const form = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      email: '',
      nickname: '',
      phone: '',
      walletAddress: '',
    });

    const validatePassword = (rule, value, callback) => {
      if (value !== form.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 50, message: '用户名长度为 3-50 个字符', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码至少 6 个字符', trigger: 'blur' },
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: validatePassword, trigger: 'blur' },
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
      ],
    };

    const getWalletAddress = async () => {
      try {
        gettingWallet.value = true;
        
        const account = web3Service.getAccount();
        if (!account) {
          const connectedAccount = await web3Service.connectWallet();
          form.walletAddress = connectedAccount;
        } else {
          form.walletAddress = account;
        }
        
        ElMessage.success('钱包地址获取成功！');
      } catch (error) {
        ElMessage.error(error.message || '获取钱包地址失败');
      } finally {
        gettingWallet.value = false;
      }
    };

    const handleRegister = async () => {
      console.log('🔵 ========== 开始注册流程 ==========');
      console.log('🔵 formRef:', formRef.value);
      
      if (!formRef.value) {
        console.log('❌ formRef 不存在，退出');
        return;
      }

      try {
        console.log('🔵 开始验证表单...');
        await formRef.value.validate();
        console.log('✅ 表单验证通过');
        
        loading.value = true;
        console.log('🔵 设置 loading = true');

        const userData = {
          username: form.username.trim(),
          password: form.password,
          email: form.email?.trim() || null,
          nickname: form.nickname?.trim() || null,
          phone: form.phone?.trim() || null,
          walletAddress: form.walletAddress?.trim() || null,
        };
        
        console.log('🔵 准备发送注册请求，数据:', userData);
        const response = await userStore.actions.register(userData);
        console.log('🔵 注册响应:', response);
        
        if (response.success) {
          ElMessage.success('注册成功！欢迎加入数字藏品平台');
          console.log('✅ 注册成功，当前用户:', userStore.state.user);
          console.log('✅ 登录状态:', userStore.state.isLoggedIn);
          console.log('✅ Token:', userStore.state.token);
          
          // 等待 Vue 响应式系统更新完成
          await nextTick();
          
          // 延迟跳转到主页
          setTimeout(async () => {
            console.log('🚀 准备跳转到主页');
            
            try {
              await router.push('/');
              console.log('✅ 跳转成功');
            } catch (err) {
              console.error('❌ 跳转失败:', err);
              // 如果跳转失败，尝试强制刷新
              window.location.href = '/';
            }
          }, 300);
        } else {
          ElMessage.error(response.message || '注册失败');
        }
      } catch (error) {
        if (error !== false) {
          console.error('注册错误:', error);
          ElMessage.error(error.message || '注册失败');
        }
      } finally {
        loading.value = false;
      }
    };

    const goToLogin = () => {
      router.push('/login');
    };

    return {
      form,
      rules,
      formRef,
      loading,
      gettingWallet,
      getWalletAddress,
      handleRegister,
      goToLogin,
    };
  },
};
</script>

<style scoped>
.auth-container {
  min-height: calc(100vh - 80px);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

.auth-card {
  width: 100%;
  max-width: 550px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.auth-header {
  text-align: center;
}

.auth-header h2 {
  margin: 0 0 0.5rem 0;
  color: #303133;
}

.auth-header p {
  margin: 0;
  color: #909399;
  font-size: 0.9rem;
}
</style>

